package com.jmu.bishe.service;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jmu.bishe.dao.SimpleHibernateDao;
import com.jmu.bishe.entity.Member;
import com.jmu.bishe.entity.News;
import com.jmu.bishe.utils.BeanUtils;
import com.jmu.bishe.utils.StringUtils;
import com.jmu.bishe.utils.UUIDGenerator;


@Service
@Transactional
public class NewsService {
	
	private static Logger logger = Logger.getLogger(NewsService.class);

	
	private SimpleHibernateDao<News, String> newsDao;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		//初始化DAO
	
		newsDao = new SimpleHibernateDao<News, String>(sessionFactory, News.class);
	}
	
	private JdbcTemplate jdbcTemplate;
	
	@Resource(name = "jdbcTemplate")
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

   
    public Boolean saveOrUpdate(News news){
    	try{    		
    		newsDao.saveOrUpdate(news);
    		return true;
    	}catch (Exception e) {
    		logger.info("保存新闻异常",e);
    		return false;
    	}    	
    	
    }
    
    /**
     * 取得新闻列表查询的条件以及条件参数
     * @return sql:String,tjs:List<String>
     */
    public Map getParamMap(HttpServletRequest request){
        String sql = "select t.*,to_char(t.record_date,'yyyy-mm-dd') DISPLAY_DATE  from news t where T.STATUS='1' ";
        List<String> tjs = new ArrayList<String>();
        
        String dateType = request.getParameter("dateType");
        if(!StringUtils.isBlank(dateType)){
        	if(dateType.equals("2")){
        		//本周
        		sql += "AND t.record_date between trunc(sysdate, 'd')-6 and  trunc(sysdate, 'd') ";
        	}else if(dateType.equals("1")){
        		//本日
        		sql += "AND trunc(sysdate)=trunc(t.record_date) ";
        	}else if(dateType.equals("3")){
        		//本月
        		sql += "AND t.record_date between trunc(sysdate, 'mm') and  last_day(trunc(sysdate)) ";
        	}else if(dateType.equals("4")){
        		//本年
        		sql += "AND t.record_date between trunc(sysdate, 'yyyy') and add_months(trunc(sysdate, 'yyyy'), 12) - 1 ";
        	}
        }else{
        	if(request.getParameter("start")!=null){
        		sql += " AND to_char(t.record_date,'yyyy-mm-dd') >= ? ";
        		tjs.add(request.getParameter("start"));
        	}
        	if(request.getParameter("end")!=null){
        		sql += " AND to_char(t.record_date,'yyyy-mm-dd') <= ? ";
        		tjs.add(request.getParameter("end"));
        	}
        }
        
        String keywords = request.getParameter("keywords");
        
        if(!StringUtils.isBlank(keywords)){
        	try {
    			keywords = URLDecoder.decode(keywords,"utf-8");
    		} catch (UnsupportedEncodingException e) {
    			logger.info("中文参数编码失败！",e);
    		}
            sql += "AND T.CONTENT like '%"+keywords+"%' ";
        }       
       
        sql += "  order by t.record_date desc ";
        Map map = new HashMap();
        map.put("sql",sql);
        map.put("tjs",tjs);
        return map;
    }


	public News getNews(String nid) {
		// TODO Auto-generated method stub
		News news = newsDao.get(nid);
		return news;
	}
	
	/**
     * 取得我的新闻列表查询的条件以及条件参数
     * @return sql:String,tjs:List<String>
     */
    public Map getMyNewsParamMap(HttpServletRequest request,Member m){    	
    	String sql = "";
    	List<String> tjs = new ArrayList<String>();
    	if("0".equals(m.getRole())){
    		//0是超级管理员，可以取到所有的新闻列表
    		sql = "select t.*,to_char(t.record_date,'yyyy-mm-dd') DISPLAY_DATE  from news t where 1=1 ";
    	}else{
    		sql = "select t.*,to_char(t.record_date,'yyyy-mm-dd') DISPLAY_DATE  from news t where user_id=? ";
    		 tjs.add(m.getUserId());
    	}
                
        String keywords = request.getParameter("keywords");
        
        if(!StringUtils.isBlank(keywords)){
        	try {
    			keywords = URLDecoder.decode(keywords,"utf-8");
    		} catch (UnsupportedEncodingException e) {
    			logger.info("中文参数编码失败！",e);
    		}
            sql += "AND T.Title like '%"+keywords+"%' ";
        }       
       
        sql += "  order by t.record_date desc ";
        Map map = new HashMap();
        map.put("sql",sql);
        map.put("tjs",tjs);
        return map;
    }

    /**
     * 删除ids的新闻，ids有多个由逗号隔开
     * @param ids
     * @return
     */
    public boolean deleteNews(String ids,String userId){
    	String[] arr = ids.split(",");
    	for(String s : arr){    		
    		if(!StringUtils.isBlank(s)){
    			News temp = newsDao.get(s);
        		if(temp!=null){
        			if(temp.getUserId().equals(userId)){
        				newsDao.delete(s);
        			}
        		}
    		}
    	}
    	return true;
    }
    
    /**
     * 通过审核
     * @param ids
     * @return
     */
    public boolean checkedNews(String ids){
    	String[] arr = ids.split(",");
    	for(String s : arr){    		
    		if(!StringUtils.isBlank(s)){
    			News temp = newsDao.get(s);
        		if(temp!=null){
        			temp.setStatus(1);
        		}
    		}
    	}
    	return true;
    }
    
}
